// pages/index/alarm/setAlarm/setalarm.js
const api = require('../../../../utils/api')
const util = require('../../../../utils/util')
const app = getApp()
const date = new Date()
const hours = []
const hours_2 = []
const mintues = []
const mintues_2 = []
const days = []

for (let i = 0; i <= 23; i++) {
    hours.push(i < 10 ? '0' + i : i)
    hours_2.push(i < 10 ? '0' + i : i)
}

for (let i = 0; i <= 59; i++) {
    mintues.push(i < 10 ? '0' + i : i)
    mintues_2.push(i < 10 ? '0' + i : i)
}

for (let i = 1; i <= 31; i++) {
    days.push(i)
}
Page({

    /**
     * 页面的初始数据
     */
    data: {
        hours,
        mintues,
        hours_2,
        mintues_2,
        value: [0, 0],
        currentDate: '',
        // minHour: 0,
        // maxHour: 23,
        // minMinute: 0,
        dateArr: {
            year: '',
            month: '',
            day: '',
            hour: '',
            mintue: '',
            second: ''
        },
        msg: {
            content: '是否保存修改',
            title: '',
            btntext: '保存',
            tips: 1
        },
        hassaved: false,
        obj: null,
        setFlag: false,
        dialogShow2: false,
        // filter(type, options) {
        //     let hour = new Date().getHours() //当前小时
        //     let mintue = new Date().getMinutes()
        //     let tempHour = '' //选择表中的小时
        //     if (type === 'hour') {
        //         if (hour > 12) {
        //             return options.filter((option) =>
        //                 parseInt(option) < 12 || parseInt(option) > hour - 1
        //             )
        //         }
        //         if (hour < 12) {
        //             return options.filter((option) =>
        //                 parseInt(option) < 12
        //             )
        //         }
        //         console.log('options', parseInt(options))
        //     }
        //     // if (type === 'minute') {
        //     //     return options.filter((option) => option > mintue);
        //     // }
        //     return options
        // }
    },
    // onChange(event) {
    //     let temp = event.detail.getValues();
    //     let str = temp[0] + ":" + temp[1]
    //     this.setData({
    //         currentDate: str
    //     });
    //     let hour = new Date().getHours()
    //     let mintue = new Date().getMinutes()
    //     let temparr = this.data.currentDate.split(":")
    //     console.log('testcontent', temparr, this.data.currentDate, hour, mintue, this.data.dateArr.day)
    //     if (hour !== parseInt(temparr[0])) {
    //         this.setData({
    //             minMinute: 0,
    //             // currentDate: event.detail.getColumnValue(0) + ':' + (mintue < 10 ? '0' + (mintue) : (mintue))
    //         })
    //     } else {
    //         this.setData({
    //             minMinute: mintue + 1
    //         })
    //     }
    // },
    bindChange(e) {
        const val = e.detail.value
        console.log('value1111', val)
        let min = this.data.mintues[val[1]] //当前分钟
        console.log('min', min)
        if (this.data.hours[val[0]] == this.data.dateArr.hour) { //选中小时==当前小时
            let temp = mintues.filter(item =>
                parseInt(item) > new Date().getMinutes()
            )
            console.log('temp', temp)
            if (temp.length >= 2) {
                this.setData({
                    mintues: temp
                })
            } else {
                let temp0 = this.data.hours.filter(item => parseInt(item) == hour)
                this.setData({
                    hours: temp0
                })
            }
            this.data.mintues.forEach((item, index) => {
                if (this.data.mintues.indexOf(min) != -1) {
                    console.log('sss', min, item)
                    if (item == min) {
                        val[1] = index
                    }
                } else {
                    val[1] = 0
                }
            })
            this.setData({
                'value[0]': val[0],
                'value[1]': val[1],
                currentDate: this.data.hours[val[0]] + ':' + this.data.mintues[val[1]]
            })
        } else {
            this.setData({
                mintues: mintues,
            })
            this.data.mintues.forEach((item, index) => {
                if (this.data.mintues.indexOf(min) != -1) {
                    console.log('sss', min, item)
                    if (item == min) {
                        val[1] = index
                    }
                }
            })
            this.setData({
                'value[0]': val[0],
                'value[1]': val[1],
                mintues: mintues,
                currentDate: this.data.hours[val[0]] + ':' + this.data.mintues[val[1]]
            })
        }
        console.log('currentDate', this.data.value, this.data.currentDate)
    },
    //初始化时间
    initTime() {
        let temphour = []
        let tempmin = []
        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let mintue = date.getMinutes()
        let second = date.getSeconds()
        let time = (hour < 10 ? '0' + hour : hour) + ':' + (mintue < 10 ? '0' + (mintue + 1) : (mintue + 1))
        console.log('time', (hour < 10 ? '0' + hour : hour) + ':' + (mintue < 10 ? '0' + mintue : mintue))
        this.setData({
            'dateArr.year': year,
            'dateArr.month': month < 10 ? '0' + month : month,
            'dateArr.day': day < 10 ? '0' + day : day,
            'dateArr.hour': hour < 10 ? '0' + hour : hour,
            'dateArr.mintue': mintue < 10 ? '0' + mintue : mintue,
            'dateArr.second': second < 10 ? '0' + second : second,
        })
        if (!this.data.setFlag) { //新增闹钟情况下的初始化
            let temp2 = []
            if (hour >= 12) {
                temp2 = hours.filter(item =>
                    parseInt(item) < 12 || parseInt(item) >= hour
                )
            } else {
                temp2 = hours.filter(item =>
                    parseInt(item) < 12 && parseInt(item) >= hour
                )
            }
            this.setData({
                hours: temp2
            })
            let temp = mintues.filter(item =>
                parseInt(item) > mintue
            )
            console.log('temp', temp)
            if (temp.length >= 2) {
                this.setData({
                    mintues: temp
                })
            } else {
                let temp0 = this.data.hours.filter(item => {
                    if (this.data.dateArr.hour < 12) {
                        return parseInt(item) > hour
                    } else {
                        return parseInt(item) != hour
                    }
                })
                this.setData({
                    hours: temp0
                })
            }
            temphour = this.data.hours
            tempmin = this.data.mintues
            temphour = temphour.map((val) => {
                return parseInt(val)
            })
            tempmin = tempmin.map((val) => {
                return parseInt(val)
            })
            console.log('temphour', temphour, tempmin, this.data.hours, hour)
            temphour.forEach((item, index) => {
                if (temphour.indexOf(hour) == -1) {
                    console.log('res', 'none')
                    if (item == hour + 1) {
                        this.setData({
                            'value[0]': index
                        })
                    }
                } else {
                    console.log('res', 'had')
                    if (item == hour) {
                        this.setData({
                            'value[0]': index
                        })
                    }
                }
            })
            tempmin.forEach((item, index) => {
                if (temphour.indexOf(hour) == -1) {
                    if (item == mintue) {
                        this.setData({
                            'value[1]': 0
                        })
                    }
                } else {
                    if (item == mintue) {
                        this.setData({
                            'value[1]': index
                        })
                    }
                }
            })
            this.setData({
                currentDate: this.data.hours[this.data.value[0]] + ':' + this.data.mintues[this.data.value[1]]
            })
        } else {
            let temp2 = []
            if (hour >= 12) {
                temp2 = hours.filter(item =>
                    parseInt(item) < 12 || parseInt(item) >= hour
                )
            } else {
                temp2 = hours.filter(item =>
                    parseInt(item) < 12 && parseInt(item) >= hour
                )
            }
            this.setData({
                hours: temp2
            })
            let obj = this.data.obj
            if (parseInt(obj.timearr[0]) == hour) {
                let temp = mintues.filter(item =>
                    parseInt(item) > mintue
                )
                console.log('temp', temp)
                this.setData({
                    mintues: temp
                })
            }
            let temphour = this.data.hours
            let tempmin = this.data.mintues
            temphour.forEach((item, index) => {
                if (item == parseInt(obj.timearr[0])) {
                    this.setData({
                        'value[0]': index
                    })
                }
            })
            tempmin.forEach((item, index) => {
                if (item == parseInt(obj.timearr[1])) {
                    this.setData({
                        'value[1]': index
                    })
                }
            })
        }
        // let temparr = this.data.currentDate.split(":")
        // console.log('parseInt(temparr[0])', temparr, mintue)
        // if (hour == parseInt(temparr[0])) {
        //     this.setData({
        //         minMinute: mintue + 1
        //     })
        // }
    },
    //修改/新增 闹钟
    save() {
        const page = getCurrentPages()
        console.log('page', page)
        const _this = this
        let dateArr = this.data.dateArr
        let value = this.data.value
        let temp = this.data.currentDate.split(':')
        console.log('currentDate', this.data.currentDate)
        if (!this.data.setFlag) {
            //新增
            let data = {}
            let hour = this.data.hours[value[0]]
            // let mintue = this.data.mintues[value[1]]
            if (hour < 12) {
                if (this.data.dateArr.hour < 12) {
                    data.cron = util.getToday() + ' ' + this.data.currentDate + ':00'
                } else {
                    data.cron = util.getTomorrow() + ' ' + this.data.currentDate + ':00'
                }
            } else {
                data.cron = util.getToday() + ' ' + this.data.currentDate + ':00'
            }
            api.addAlarmClock(data, app.globalData.token).then(res => {
                if (res.data.code == 200) {
                    console.log('success res====>', res.data)
                    app.globalData.hasalarm = true
                    console.log('_route_', page[page.length - 2])
                    if (page[page.length - 2].__route__ == "pages/index/index") {
                        _this.setData({
                            hassaved: true
                        })
                        wx.redirectTo({
                            url: "/pages/index/alarm/alarm"
                        })
                    } else {
                        _this.setData({
                            hassaved: true
                        })
                        wx.navigateBack()
                    }

                } else if (res.data.code == 721) {
                    wx.showToast({
                        title: '相同时间的柔性唤醒已存在',
                        icon: 'none',
                        duration: 3000
                    })
                } else if (res.data.code == 722) {
                    wx.showToast({
                        title: '无法设置历史时间的柔性唤醒',
                        icon: 'none',
                        duration: 3000
                    })
                } else {
                    util.myShowToast(res.data.msg)
                    console.log('failed error====> ', res.data.msg)
                }
            })
        } else {
            //修改
            let data = {}
            let cron = ''
            let hours_old = parseInt(this.data.obj.timearr[0]) //原来的小时
            let hours_new = parseInt(temp[0]) //更新后的小时
            let min_old = parseInt(this.data.obj.timearr[1])
            let min_new = parseInt(temp[1])
            if (this.data.obj != null) {
                if (hours_new == hours_old && min_old == min_new) {
                    wx.navigateBack()
                    return
                }
                // if (hours_new <= hours_old) {
                if (hours_new < this.data.dateArr.hour) {
                    cron = util.getTomorrow() + ' ' + this.data.currentDate + ':00'
                } else {
                    cron = util.getToday() + ' ' + this.data.currentDate + ':00'
                }
                // } else {
                //     if (hours_new < this.data.dateArr.hour) {
                //         cron = util.getTomorrow() + ' ' + this.data.currentDate + ':00'
                //     } else {
                //         cron = util.getToday() + ' ' + this.data.currentDate + ':00'
                //     }
                // }
            } else {}
            data = {
                id: this.data.obj.id,
                cron: cron
            }
            console.log('datasssss', data)
            api.updateAlarmClock(data, app.globalData.token).then(res => {
                if (res.data.code == 200) {
                    console.log('success res===>', res.data.data)
                    _this.setData({
                        hassaved: true
                    })
                    wx.navigateBack()
                } else if (res.data.code == 721) {
                    wx.showToast({
                        title: '相同时间的柔性唤醒已存在',
                        icon: 'none',
                        duration: 3000
                    })
                } else if (res.data.code == 722) {
                    wx.showToast({
                        title: '无法设置历史时间的柔性唤醒',
                        icon: 'none',
                        duration: 3000
                    })
                } else {
                    util.myShowToast(res.data.msg)
                    console.log('failed error====> ', res.data.msg)
                }
            })
        }
    },

    //取消/删除闹钟
    cancel() {
        const _this = this
        if (this.data.setFlag == false) {
            wx.navigateBack()
        } else {
            this.setData({
                dialogShow2: true,
                'msg.content': '是否确认删除',
                'msg.btntext': '手滑了',
                'msg.btntext_0': '确认',
                'msg.tips': 4
            })
        }
    },

    dialogHandle2(e) {
        this.setData({
            dialogShow2: e.detail.params
        })
        if (e.detail.text == 'confirm') {
            if (this.data.msg.btntext_0 == '确认') {
                let data = {
                    id: this.data.obj.id
                }
                api.deleteAlarmClock(data, app.globalData.token).then(res => {
                    if (res.data.code == 200) {
                        console.log('delete success')
                        wx.navigateBack()
                    } else {
                        util.myShowToast(res.data.msg)
                        console.log('failed error====> ', res.data.msg)
                    }
                })
            }
        }
    },
    BeaforeUnLoad() {
        wx.enableAlertBeforeUnload({
            message: '是否保存修改',
            success: (e) => {
                console.log('success', e);
            },
            fail: (e) => {
                console.log('failed', e);
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.obj) {
            let obj = JSON.parse(options.obj)
            console.log('obj', obj)
            let day = new Date(obj.cron).getDate()
            let timearr = obj.time.split(':')
            obj.timearr = timearr
            obj.day = day
            console.log('timearr', timearr)
            this.setData({
                obj: obj,
                currentDate: obj.time,
                setFlag: true
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.initTime()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})